package com.example.weight.greenSeasons.waterDeal;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class EquipmentCheckTable_old extends AppCompatActivity {
        private ExpandableLayout expand_1;
        private Button textView1;
        private ExpandableLayout expand_2;
        private Button textView2;
        private TextView dateEdit;

        private TitleBar titleBar;

        //用户、抄表人
        private String name, role, factory;
        //设备名称
        private TextView name1,name2,name3,name4,name5,name6,name7;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_equipment_check_table_old);

                //用户和职责
            Intent previousIntent = getIntent();
            name = previousIntent.getStringExtra("name");
            role = previousIntent.getStringExtra("role");
            factory = previousIntent.getStringExtra("factory");

            //正常异常按钮组
            RadioGroup radioGroup1 = findViewById(R.id.equipment1_group_button);
            RadioGroup radioGroup2 = findViewById(R.id.equipment2_group_button);
            RadioGroup radioGroup3 = findViewById(R.id.equipment3_group_button);
            RadioGroup radioGroup4 = findViewById(R.id.equipment4_group_button);
            RadioGroup radioGroup5 = findViewById(R.id.equipment5_group_button);
            RadioGroup radioGroup6 = findViewById(R.id.equipment6_group_button);
            RadioGroup radioGroup7 = findViewById(R.id.equipment7_group_button);

            //所有正常异常按钮
            RadioButton btn1_1 = findViewById(R.id.equipment1_normal_button);
            RadioButton btn1_0 = findViewById(R.id.equipment1_abnormal_button);
            RadioButton btn2_1 = findViewById(R.id.equipment2_normal_button);
            RadioButton btn2_0 = findViewById(R.id.equipment2_abnormal_button);
            RadioButton btn3_1 = findViewById(R.id.equipment3_normal_button);
            RadioButton btn3_0 = findViewById(R.id.equipment3_abnormal_button);
            RadioButton btn4_1 = findViewById(R.id.equipment4_normal_button);
            RadioButton btn4_0 = findViewById(R.id.equipment4_abnormal_button);
            RadioButton btn5_1 = findViewById(R.id.equipment5_normal_button);
            RadioButton btn5_0 = findViewById(R.id.equipment5_abnormal_button);
            RadioButton btn6_1 = findViewById(R.id.equipment6_normal_button);
            RadioButton btn6_0 = findViewById(R.id.equipment6_abnormal_button);
            RadioButton btn7_1 = findViewById(R.id.equipment7_normal_button);
            RadioButton btn7_0 = findViewById(R.id.equipment7_abnormal_button);

            //设备名称
            name1=findViewById(R.id.name1);
            name2=findViewById(R.id.name2);
            name3=findViewById(R.id.name3);
            name4=findViewById(R.id.name4);
            name5=findViewById(R.id.name5);
            name6=findViewById(R.id.name6);
            name7=findViewById(R.id.name7);

            //下拉框
            expand_1=findViewById(R.id.expandable_1);
            textView1=findViewById(R.id.button_1);

            expand_2=findViewById(R.id.expandable_2);
            textView2=findViewById(R.id.button_2);
            //日期
            dateEdit=findViewById(R.id.compost_editDate);
            Calendar calendar=Calendar.getInstance();
            Integer year = calendar.get(Calendar.YEAR);
            Integer month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
            Integer day = calendar.get(calendar.DAY_OF_MONTH);
            Integer hour24 = calendar.get(calendar.HOUR_OF_DAY);
            Integer minute = calendar.get(calendar.MINUTE);
            dateEdit.setText(year+"-"+month+"-"+day);
            //标题返回按钮
            titleBar=findViewById(R.id.titleBar);
            titleBar.setOnTitleBarListener(new OnTitleBarListener() {
                @Override
                //操作人——如果还有未操作的，提示用户，直到所有都操作
                public void onLeftClick(View v) {
                    if (radioGroup1.getCheckedRadioButtonId() == -1) {
                        allDone(name1.getText().toString());
                    }else if (radioGroup2.getCheckedRadioButtonId() == -1) {
                        allDone(name2.getText().toString());
                    }else if (radioGroup3.getCheckedRadioButtonId() == -1) {
                        allDone(name3.getText().toString());
                    }else if (radioGroup4.getCheckedRadioButtonId() == -1) {
                        allDone(name4.getText().toString());
                    }else if (radioGroup5.getCheckedRadioButtonId() == -1) {
                        allDone(name5.getText().toString());
                    }else if (radioGroup6.getCheckedRadioButtonId() == -1) {
                        allDone(name6.getText().toString());
                    }else if (radioGroup7.getCheckedRadioButtonId() == -1) {
                        allDone(name7.getText().toString());
                    }else {
                        EquipmentCheckTable_old.this.finish();
                    }
                }
                @Override
                public void onTitleClick(View v) {
                }
                @Override
                public void onRightClick(View v) {
                }
            });

            //equip_1
            btn1_1.setOnClickListener(v -> {
                if (btn1_1.isChecked()) {
                    saveNormal(name1.getText().toString(), btn1_0, btn1_1,radioGroup1);
                }
            });
            btn1_0.setOnClickListener(v -> {
                if (btn1_0.isChecked()) {
                    saveAbnormal(name1.getText().toString(), btn1_0, btn1_1,radioGroup1);
                }
            });
            //equip_2
            btn2_1.setOnClickListener(v -> {
                if (btn2_1.isChecked()) {
                    saveNormal(name2.getText().toString(), btn2_0, btn2_1,radioGroup2);
                }
            });
            btn2_0.setOnClickListener(v -> {
                if (btn2_0.isChecked()) {
                    saveAbnormal(name2.getText().toString(), btn2_0, btn2_1,radioGroup2);
                }
            });
            //equip_3
            btn3_1.setOnClickListener(v -> {
                if (btn3_1.isChecked()) {
                    saveNormal(name3.getText().toString(), btn3_0, btn3_1,radioGroup3);
                }
            });
            btn3_0.setOnClickListener(v -> {
                if (btn3_0.isChecked()) {
                    saveAbnormal(name3.getText().toString(), btn3_0, btn3_1,radioGroup3);
                }
            });
            //equip_4
            btn4_1.setOnClickListener(v -> {
                if (btn4_1.isChecked()) {
                    saveNormal(name4.getText().toString(), btn4_0, btn4_1,radioGroup4);
                }
            });
            btn4_0.setOnClickListener(v -> {
                if (btn4_0.isChecked()) {
                    saveAbnormal(name4.getText().toString(), btn4_0, btn4_1,radioGroup4);
                }
            });
            //equip_5
            btn5_1.setOnClickListener(v -> {
                if (btn5_1.isChecked()) {
                    saveNormal(name5.getText().toString(), btn5_0, btn5_1,radioGroup5);
                }
            });
            btn5_0.setOnClickListener(v -> {
                if (btn5_0.isChecked()) {
                    saveAbnormal(name5.getText().toString(), btn5_0, btn5_1,radioGroup5);
                }
            });
            //equip_6
            btn6_1.setOnClickListener(v -> {
                if (btn6_1.isChecked()) {
                    saveNormal(name6.getText().toString(), btn6_0, btn6_1,radioGroup6);
                }
            });
            btn6_0.setOnClickListener(v -> {
                if (btn6_0.isChecked()) {
                    saveAbnormal(name6.getText().toString(), btn6_0, btn6_1,radioGroup6);
                }
            });
            //equip_7
            btn7_1.setOnClickListener(v -> {
                if (btn7_1.isChecked()) {
                    saveNormal(name7.getText().toString(), btn7_0, btn7_1,radioGroup7);
                }
            });
            btn7_0.setOnClickListener(v -> {
                if (btn7_0.isChecked()) {
                    saveAbnormal(name7.getText().toString(), btn7_0, btn7_1,radioGroup7);
                }
            });

            //获取当天最新一条数据
            RequestQueue queue = Volley.newRequestQueue(this);
//            String url = Config.url + "/shlj/sjqCompostProduceInspection/getlast_day";
            String url = Config.url + "/sjq/SjqWaterProductionInspectionEquipment/getLast" + "?factory=" + factory;

            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                Log.d("jy", response);
                                JSONArray data;
                                if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")) {
                                    data = jsonObject.getJSONArray("data");
                                    if(data.length()>0){
                                        for(int i=0;i<data.length();i++){
                                            // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                            JSONObject record = data.getJSONObject(i);
                                            // 得到 每个对象中的属性值
                                            if (record.get("equipmentName").equals(name1.getText().toString())){
                                                if(record.get("isNormal").equals("正常")){
                                                    btn1_1.setChecked(true);
                                                }else {
                                                    btn1_0.setChecked(true);
                                                }
                                                if(record.get("operator")!=null){
                                                    btn1_1.setClickable(false);
                                                    btn1_0.setClickable(false);
                                                }
                                            }else if (record.get("equipmentName").equals(name2.getText().toString())){
                                                if(record.get("isNormal").equals("正常")){
                                                    btn2_1.setChecked(true);
                                                }else {
                                                    btn2_0.setChecked(true);
                                                }
                                                if(record.get("operator")!=null){
                                                    btn2_1.setClickable(false);
                                                    btn2_0.setClickable(false);
                                                }
                                            }else if (record.get("equipmentName").equals(name3.getText().toString())){
                                                if(record.get("isNormal").equals("正常")){
                                                    btn3_1.setChecked(true);
                                                }else {
                                                    btn3_0.setChecked(true);
                                                }
                                                if(record.get("operator")!=null){
                                                    btn3_1.setClickable(false);
                                                    btn3_0.setClickable(false);
                                                }
                                            }else if (record.get("equipmentName").equals(name4.getText().toString())){
                                                if(record.get("isNormal").equals("正常")){
                                                    btn4_1.setChecked(true);
                                                }else {
                                                    btn4_0.setChecked(true);
                                                }
                                                if(record.get("operator")!=null){
                                                    btn4_1.setClickable(false);
                                                    btn4_0.setClickable(false);
                                                }
                                            }else if (record.get("equipmentName").equals(name5.getText().toString())){
                                                if(record.get("isNormal").equals("正常")){
                                                    btn5_1.setChecked(true);
                                                }else {
                                                    btn5_0.setChecked(true);
                                                }
                                                if(record.get("operator")!=null){
                                                    btn5_1.setClickable(false);
                                                    btn5_0.setClickable(false);
                                                }
                                            }else if (record.get("equipmentName").equals(name6.getText().toString())){
                                                if(record.get("isNormal").equals("正常")){
                                                    btn6_1.setChecked(true);
                                                }else {
                                                    btn6_0.setChecked(true);
                                                }
                                                if(record.get("operator")!=null){
                                                    btn6_1.setClickable(false);
                                                    btn6_0.setClickable(false);
                                                }
                                            }else if (record.get("equipmentName").equals(name7.getText().toString())){
                                                if(record.get("isNormal").equals("正常")){
                                                    btn7_1.setChecked(true);
                                                }else {
                                                    btn7_0.setChecked(true);
                                                }
                                                if(record.get("operator")!=null){
                                                    btn7_1.setClickable(false);
                                                    btn7_0.setClickable(false);
                                                }
                                            }
                                        }
                                    }
                                }
                            /*
                            radioGroup1.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name1.getText().toString(),btn1_0,btn1_1,radioGroup1);
                                }else {
                                    saveAbnormal(name1.getText().toString(),btn1_0,btn1_1,radioGroup1);
                                }

                            });
                            radioGroup2.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name2.getText().toString(),btn2_0,btn2_1,radioGroup2);
                                }else {
                                    saveAbnormal(name2.getText().toString(),btn2_0,btn2_1,radioGroup2);
                                }

                            });
                            radioGroup3.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name3.getText().toString(),btn3_0,btn3_1,radioGroup3);
                                }else {
                                    saveAbnormal(name3.getText().toString(),btn3_0,btn3_1,radioGroup3);
                                }

                            });
                            radioGroup4.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name4.getText().toString(),btn4_0,btn4_1,radioGroup4);
                                }else {
                                    saveAbnormal(name4.getText().toString(),btn4_0,btn4_1,radioGroup4);
                                }

                            });
                            radioGroup5.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name5.getText().toString(),btn5_0,btn5_1,radioGroup5);
                                }else {
                                    saveAbnormal(name5.getText().toString(),btn5_0,btn5_1,radioGroup5);
                                }

                            });
                            radioGroup6.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name6.getText().toString(),btn6_0,btn6_1,radioGroup6);
                                }else {
                                    saveAbnormal(name6.getText().toString(),btn6_0,btn6_1,radioGroup6);
                                }

                            });
                            radioGroup7.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name7.getText().toString(),btn7_0,btn7_1,radioGroup7);
                                }else {
                                    saveAbnormal(name7.getText().toString(),btn7_0,btn7_1,radioGroup7);
                                }

                            });
                            radioGroup8.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name8.getText().toString(),btn8_0,btn8_1,radioGroup8);
                                }else {
                                    saveAbnormal(name8.getText().toString(),btn8_0,btn8_1,radioGroup8);
                                }

                            });
                            radioGroup9.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name9.getText().toString(),btn9_0,btn9_1,radioGroup9);
                                }else {
                                    saveAbnormal(name9.getText().toString(),btn9_0,btn9_1,radioGroup9);
                                }

                            });
                            radioGroup10.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name10.getText().toString(),btn10_0,btn10_1,radioGroup10);
                                }else {
                                    saveAbnormal(name10.getText().toString(),btn10_0,btn10_1,radioGroup10);
                                }

                            });
                            radioGroup11.setOnCheckedChangeListener((group, checkedId) -> {
                                RadioButton button = findViewById(checkedId);
                                String isNormal = button.getText().toString();
                                if (isNormal.equals("正常")){
                                    saveNormal(name11.getText().toString(),btn11_0,btn11_1,radioGroup11);
                                }else {
                                    saveAbnormal(name11.getText().toString(),btn11_0,btn11_1,radioGroup11);
                                }

                            });*/
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(EquipmentCheckTable_old.this,
                            "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(stringRequest);


        }

        public void show1(View view) {
            if (expand_1.isExpanded()){
                textView1.setText("+ 气动阀");
            }else{
                textView1.setText("- 气动阀");
            }
            expand_1.toggle();
        }

    public void show2(View view) {
        if (expand_2.isExpanded()){
            textView2.setText("+ 膜组件");
        }else{
            textView2.setText("- 膜组件");
        }
        expand_2.toggle();
    }

        public void saveNormal(String equipment_name, RadioButton normal_rb, RadioButton abnormal_rb,RadioGroup rb) {
            new AlertDialog.Builder(this)
                    .setTitle("确定 “"+ equipment_name +"” 正常？")
                    .setCancelable(false)
                    .setNegativeButton("否", ((dialog, which) ->{
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                        rb.clearCheck();
                    }))
                    .setPositiveButton("是", (dialog, which) ->{
                        // 提交表单
                        RequestQueue queue = Volley.newRequestQueue(this);
//                        String url = Config.url + "/shlj/sjqCompostProduceInspection/add_recorder";
                        String url = Config.url + "/sjq/SjqWaterProductionInspectionEquipment/addOperator";
                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        Log.d("zys", response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String code = jsonObject.getString("code");
                                            if (code.equals("200")){
                                                normal_rb.setClickable(false);
                                                abnormal_rb.setClickable(false);
                                                Toast.makeText(EquipmentCheckTable_old.this,
                                                        "保存成功", Toast.LENGTH_SHORT).show();
                                            }
                                            else
                                                Toast.makeText(EquipmentCheckTable_old.this,
                                                        "保存失败", Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(EquipmentCheckTable_old.this,
                                        "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }) {
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                Map<String, String> map=new HashMap<>();
                                map.put("equipment_name", equipment_name);
                                map.put("is_normal","正常");
                                map.put("remarks", "");
                                map.put("operator", name);
                                map.put("factory", factory);
                                return map;
                            }
                        };
                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                        queue.add(stringRequest);
                    })
                    .show();
        }

        public void saveAbnormal(String equipment_name, RadioButton normal_rb, RadioButton abnormal_rb,RadioGroup rb) {
            final EditText equipment_problem = new EditText(this);
            equipment_problem.setHint("   输入问题:");
            new AlertDialog.Builder(this)
                    .setTitle("请填写 “"+ equipment_name +"” 异常原因？")
                    .setView(equipment_problem)
                    .setCancelable(false)
                    .setNegativeButton("取消", ((dialog, which) ->{
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                        rb.clearCheck();
                    }
                    ))
                    .setPositiveButton("提交", (dialog, which) ->{
                        // 提交表单
                        RequestQueue queue = Volley.newRequestQueue(this);
//                        String url = Config.url + "/shlj/sjqCompostProduceInspection/add_recorder";
                        String url = Config.url + "/sjq/SjqWaterProductionInspectionEquipment/addOperator";
                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        Log.d("jy", response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String code = jsonObject.getString("code");
                                            if (code.equals("200")){
                                                normal_rb.setClickable(false);
                                                abnormal_rb.setClickable(false);
                                                Toast.makeText(EquipmentCheckTable_old.this,
                                                        "保存成功", Toast.LENGTH_SHORT).show();
                                            }
                                            else
                                                Toast.makeText(EquipmentCheckTable_old.this,
                                                        "保存失败", Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(EquipmentCheckTable_old.this,
                                        "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }) {
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                Map<String, String> map=new HashMap<>();
                                map.put("equipment_name", equipment_name);
                                map.put("is_normal","异常");
                                map.put("remarks", equipment_problem.getText().toString());
                                map.put("operator", name);
                                map.put("factory", factory);
                                return map;
                            }
                        };
                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                        queue.add(stringRequest);
                    })
                    .show();
        }
        public void allDone(String equipment_name){
            new AlertDialog.Builder(this)
                    .setTitle(" “"+ equipment_name +"” 未检查，是否退出")
                    .setCancelable(false)
                    .setNegativeButton("否", ((dialog, which) -> {
                        return;
                    }))
                    .setPositiveButton("是", (dialog, which) ->{
                        EquipmentCheckTable_old.this.finish();
                    })
                    .show();
        }

}